package cs271.examples.oop;

import java.math.BigInteger;

/**
 * Here we look at identity versus equality.  Objects references that point
 * to the same object in memory are said to be identical.  We can check equality
 * using the == operator.  We can compare two objects in memory logically using
 * .equals(...) method.
 *
 * @author mbone
 */
public class EqualityVsIdentity {
    
    public static void main(String[] args) {
        BigInteger int1 = new BigInteger("100");
        BigInteger int2 = new BigInteger("100");
        BigInteger int3 = new BigInteger("200");
        BigInteger int4 = int3;
        
        System.out.println("int1: " + int1);
        System.out.println("int2: " + int2);
        System.out.println("int3: " + int3);
        System.out.println("int4: " + int4);
        
        //int1 and int2 are logically equivalent:
        System.out.println("int1.equals(int2): " + int1.equals(int2));
        //but not identical because they do not point to the same object in memory
        System.out.println("int1==int2: " + (int1==int2));
        
        //int3 and int4 are identical because they _do_ point to the same object in memory
        System.out.println("int3==int4: " + (int3==int4));
        System.out.println("int3.equals(int4): " + int3.equals(int4));
        
        //Now look what happens when we change the values and reapeat the tests:
        int1.add(new BigInteger("5"));
        int3.add(new BigInteger("42"));
        
        System.out.println();
        
        System.out.println("int1: " + int1);
        System.out.println("int2: " + int2);
        System.out.println("int3: " + int3);
        System.out.println("int4: " + int4); //int 4 still has the same value as int3
        
        //int1 and int2 are no longer logically equivalent
        System.out.println("int1.equals(int2): " + int1.equals(int2));
        System.out.println("int1==int2: " + (int1==int2));
        System.out.println("int3==int4: " + (int3==int4));
        System.out.println("int3.equals(int4): " + int3.equals(int4));

        
        //Strings are a special case.  For now, let's ignore them.
        /*String a = "Hello";
        String b = "world";
        String c = "Hello";
        String d = b;  //d points to the SAME object in memory as b
        
        System.out.println("String a: " + a);
        System.out.println("String b: " + b);
        System.out.println("String c: " + c);
        System.out.println("String d: " + d);
        System.out.println("a.equals(c): " + a.equals(c));
        System.out.println("a == c: " + (a==c));
        System.out.println("d.equals(b): " + d.equals(b));
        System.out.println("d == b: " + (d==b)); //thus the .equals evaluates to true, too*/
        
                
    }
}
